#!/usr/bin/python3
import cgi, os
import cgitb
from _sha1 import sha1
# Apache2 vhost 设置中已经设置了 SetENV PYTHONIOENCODING=UTF-8
# 所以无需在设置 sys.stdout 的编码方式为 utf8，否则要去掉下面两行的配置
#import sys,codecs
#sys.stdout = codecs.getwriter('utf8')(sys.stdout.buffer)
cgitb.enable()  
form = cgi.FieldStorage()
title = '#Removed#'
# path : 上传文件存储目录  
path = '/home/backup/MyShare/upload/'

def file_hash(filename):
    """ sha,size = file_hash( pathname ) """
    try:
        size = os.path.getsize(filename)
    except:
        return (None,0)
    if size>11000000:
        return (None,0)
    data=[]
    fp = open(filename,'rb')
    for line1 in fp:
        data.append(line1)
    fp.close()
    dat = b''.join(data)
    sha = sha1( dat )
    return (sha.hexdigest(),size)
    
try:
    filename = form.getvalue('remove')
    sha = form.getvalue('sha')
    size = int(form.getvalue('size'))
    # strip leading path from file name to avoid directory traversal attacks  
    fn = os.path.split(filename)
    if fn[0] != '':
        title = '#Reject#'
        raise ValueError
    else:
        # Internet Explorer will attempt to provide full path for filename fix  
        fn = fn[1]
    filepath = path + fn  
    sha1,size1 = file_hash( filepath )
    if sha1==sha and size1==size:
        os.unlink( filepath )
        message = fn
    else:
        title = '#Reject#'
        message = 'SHA1 NOT MATCH'
except Exception as e:  
    message = e
    if title == '#Removed#':
        title = '#Fail#'
    
print('Content-type:text/html;charset="utf-8"\n\n')
print( """<html>
<head><title>%s</title></head>
<body>%s</body>
</html>""" % (title,message) )
